<?php
require_once APP . '/application/controllers/FrontAction.php';
require_once APP . '/application/models/UserModel.php';
require_once APP . '/application/models/Util.php';

/**
 * 首页
 */
class IndexController extends FrontAction
{
    
    /**
     * 首页
     *
     */
    public function flashAction()
    {
    	
        $this->render("index");
    }
    
    /**
     * flash 下注
     *
     */
    public function indexAction()
    {
    	global $cfg;
    	
		require_once APP . '/application/configs/version.php';
		
		$this->view->cfg = $cfg;
    	$this->render("flash");
    }
    
    /**
     * 获取基本信息
     *
     */
    public function infoAction()
    {
    	global $cfg;
    	$result = array("status" => 1, "data" => array());
    	
    	$uid = 0;
    	if (isset($_SESSION['uid']))
    		$uid = (int)$_SESSION['uid'];
    	
    	if ($uid > 0)
    		$result['data']['uinfo'] = $this->db->fetchRow("select * from user where uid=" . $uid);
    	
    	$result['data']['beilv'] = $cfg['rate_bet_beilv'];
    	
    	echo json_encode($result);
    }
    
    /**
     * 下注页面
     *
     */
    public function betAction()
    {
    	$user = new UserModel($this->db);
    	
    	$this->view->userinfo = $user->show($_SESSION['uid']);
    	$this->view->min = $this->db->fetchOne("select value from pool where name='min'");
    	$this->view->max = $this->db->fetchOne("select value from pool where name='max'");
    	
    	$this->render("bet");
    }
    
    /**
     * 修改 TODO:删除
     *
     */
    public function setAction()
    {
    	$param = $this->getAllParams();
    	
    	if (isset($param['cash'])){
    		$this->db->update("user", array("cash" => $param['cash']), "uid=" . $_SESSION['uid']);
    	}
    	
    	if (isset($param['min'])){
    		$this->db->update("pool", array("value" => $param['min']), "name='min'");
    	}
    	if (isset($param['max'])){
    		$this->db->update("pool", array("value" => $param['max']), "name='max'");
    	}
    }
    
    /**
     * 投注处理
     *
     */
    public function dobetAction()
    {
    	global $cfg;
    	
    	$uid = (int)$_SESSION['uid'];
    	$times = (int)$this->getParam("times");
    	$flash = false;
    	
    	if ($times == 0){
    		$flash = true;
    		$times = 1;
    	}
    	
    	$arr_bet = array();
    	
    	// 投注编号为：bet_0 ... bet_7 共8个 "袁绍", "孙权", "大乔", "夏侯惇", "曹操", "关羽", "张飞", "特殊"
    	$bet_total = 0;
    	for($i=0; $i < 8; $i++){
    		$arr_bet[$i] = (int)$this->getParam("bet_" . $i);
    		if ($arr_bet[$i] < 0){    			
    			$this->showmessage(0, "下注不能为负");
    		}
    		$bet_total += $arr_bet[$i];
    	}
    	    	
    	$user = new UserModel($this->db);
    	$arr_userinfo = $user->show($uid);
    	
    	if ($bet_total <= 0){
    		$this->showmessage(0, "下注不能为空");
    	}
    	
    	if ($times <= 0)
    		$this->showmessage(0, "至少下注一次");
    	
    	if ($bet_total*$times > $arr_userinfo['cash']){
    		$this->showmessage(0, "金钱不足");
    	}
    	
    	/**
    	 * 从0
    	 * 袁绍    8分之一
			小关羽  12分之一
			小张飞  12分之一
			小大乔  12分之一
			小孙权  12分之一
			小曹操  12分之一
			小夏侯  12分之一
			大夏侯  24分之一
			大曹操  24分之一
			大孙权  24分之一
			大大乔  24分之一
			大张飞  24分之一
			大关羽  24分之一
			小特殊  12分之一
			大特殊  24分之一
    	 */
    	$cfg_rate = array(0 => 8, 1 => 12, 2=>12, 3 => 12, 4 => 12, 5 => 12, 6=>12,
    					  7 => 24, 8 => 24, 9=> 24, 10 => 24, 11 => 24, 12 => 24,
    					  13 => 12, 14 => 24);
    	// 中奖和投注图标对应 "袁绍0", "孙权1", "大乔2", "夏侯惇3", "曹操4", "关羽5", "张飞6", "特殊7"
    	$cfg_rate_bet = array(0 => 0, 1 => 5, 2=>6, 3 => 2, 4 => 1, 5 => 4, 6=>3,
    					  7 => 3, 8 => 4, 9=> 1, 10 => 2, 11 => 6, 12 => 5,
    					  13 => 7, 14 => 7);
    	// 中奖图标倍率
    	$cfg_rate_bet_beilv = $cfg['rate_bet_beilv'];
    	
   		$cfg_rate_total = array_sum($cfg_rate);
   		$cfg_rate_percent = array();// 千分比来判断 总共概率加起来=1000
   		foreach ($cfg_rate as $index => $v){
   			$cfg_rate_percent[$index] = $v / $cfg_rate_total * 1000;
   		}
   		   		
    	$pool_min = $this->db->fetchOne("select value from pool where name='min'");
    	$pool_max = $this->db->fetchOne("select value from pool where name='max'");
    	
    	// 赢的判断
    	$arr_logs = array();
    	// 用户投注记录
    	$arr_log_bet = array();
    	$arr_log_bet['uid'] = $uid;
    	$arr_log_bet['cash'] = 0;// 用户当前金钱
    	
    	foreach ($arr_bet as $key => $v)
    		$arr_log_bet["bet_" . $key] = $v;// bet_0 ... bet_7
    	
    	$arr_log_bet['pool_min'] = 0;
    	$arr_log_bet['pool_max'] = 0;
    	
    	$arr_log_bet['usemaxpool'] = false;// 是否使用大彩池
    	$arr_log_bet['open_rate'] = 0;// 系统开奖编号 0-14
    	$arr_log_bet['open_rate_bet'] = 0;// 系统开奖对应下注图标 0-7
    	$arr_log_bet['open_rate_beilv'] = 0;// 系统开奖倍率
    	$arr_log_bet['sys_max_beilv'] = 0;// 系统允许最高倍率
    	$arr_log_bet['ret_rate_bet'] = 0;// 返回中奖图标 0-14
    	
    	$arr_log_bet['bet_total'] = $bet_total;// 用户总下注
    	$arr_log_bet['user_win'] = 0;// 用户赢的
    	$arr_log_bet['user_real_win'] = 0;// 用户减去投注之后赢的	
    	
    	$arr_log_bet['pool_min_after'] = 0;
    	$arr_log_bet['pool_max_after'] = 0;
    	
    	$arr_debug = array();
    	$arr_debug2= array();
    	
    	// 中奖计算
    	for($i=0; $i < $times; $i++){
    		
    		$last_time = (int)$this->db->fetchOne("select value from pool where name='last_time'");
    		$now = time();
    		if ($now - $last_time >= 3600){// 每个1个小时执行一次
    			if ($pool_max > 20000){
    				$max_minus = intval($pool_max * 0.1);    				
	    			$this->db->update("pool", array("value" => "value-" . $max_minus), "name='max'");
	    			$pool_max -= $max_minus;
	    			
	    			$pool_min += $max_minus;
	    			if ($pool_min > 6000){
	    				$pool_min = 6000;
	    			}
	    			$this->db->update("pool", array("value" => $pool_min), "name='min'");
    			}
    			
    			$this->db->update("pool", array("value" => $now), "name='last_time'");
    		}
    		
	    	$arr_log_bet['pool_min'] = $pool_min;
	    	$arr_log_bet['pool_max'] = $pool_max;
    	
    		$open_rate = 0;// 赢的图标 0-14
    		$rand_rate = mt_rand(0, 1000);
    		
    		$rate_start = 0;
    		foreach ($cfg_rate_percent as $index => $v){
    			$rate_end = $rate_start + $v;
    			if ($rand_rate >= $rate_start && $rand_rate <= $rate_end){
    				$open_rate = $index;
    				break;
    			}
    			
    			$rate_start = $rate_end;
    		}
    		
    		// 开奖对应下注图标
    		$open_rate_bet = $cfg_rate_bet[$open_rate];
    		
    		$arr_log_bet['open_rate'] = $open_rate;
    		$arr_log_bet['open_rate_bet'] = $open_rate_bet;
    		$arr_log_bet['open_rate_beilv'] = $cfg_rate_bet_beilv[$open_rate];
    		
    		$ret_rate_bet = $open_rate;// 返回结果
    		
    		$arr_log_bet['cash'] = $arr_userinfo['cash'];
    		
    		$usermaxpool = false;
    		if ($arr_userinfo['pay'] > 100 && $arr_userinfo['cash'] > 100){
    			$usermaxpool = true;
    		}
    		$arr_log_bet['usemaxpool'] = $usermaxpool;
    		
    		if ($arr_bet[$open_rate_bet] <= 0){// 未中奖
    			// ignore
    			$arr_log_bet['sys_max_beilv'] = 0;
    		}else{// 中奖
    			$user_cash = $arr_userinfo['cash'];
    			if ($usermaxpool){// 进入大彩池
    				$cfg_pool = $cfg['maxpool'];
    				$pool_cash = $pool_max;
    			}else{// 进入小彩池
    				$cfg_pool = $cfg['minpool'];
    				$pool_cash = $pool_min;
    			}
    			
    			$max_rate = 0;
    			// 根据彩池计算是否可以中奖
    			foreach ($cfg_pool as $rate => $v){
    				if ($usermaxpool)
    				{
	    				if ($pool_cash >= $v['total'] && $arr_userinfo['pay'] >= $v['pay']){
	    					$max_rate = $rate;
	    				}else{
	    					break;
	    				}
    				}else{// 小彩池不判断 充值
    					if ($pool_cash >= $v['total']){
	    					$max_rate = $rate;
	    				}else{
	    					break;
	    				}
    				}
    			}
    			
    			$arr_log_bet['sys_max_beilv'] = $max_rate;
    			
    			if ($max_rate < $cfg_rate_bet_beilv[$open_rate]){
    				$ret_rate_bet = -1;
    			}
    		}
    		
    		if ($ret_rate_bet == -1){// 未中奖处理
    			$arr_rand_rate_bet = array();
    			foreach ($cfg_rate_bet as $sys_rate => $bet_index){
    				if ($arr_bet[$bet_index] == 0){
    					$arr_rand_rate_bet[] = $sys_rate;
    				}
    			}
    			
    			// 如果都有投注，则查找最小的
    			if (empty($arr_rand_rate_bet)){
    				$min = 1000000;
    				$min_index = 0;
    				foreach ($cfg_rate_bet as $sys_rate => $bet_index){
    					if ($arr_bet[$bet_index] * $cfg_rate_bet_beilv[$sys_rate] < $min){
    						$min = $arr_bet[$bet_index] * $cfg_rate_bet_beilv[$sys_rate];
    						$min_index = $sys_rate;
    					}
    				}
    				
    				$ret_rate_bet = $min_index;
    			}else{    				
    				$ret_rate_bet = $arr_rand_rate_bet[array_rand($arr_rand_rate_bet, 1)];
    			}
    		}
    		
    		$arr_log_bet['ret_rate_bet'] = $ret_rate_bet;
    		
    		$user_win = $arr_bet[$cfg_rate_bet[$ret_rate_bet]] * $cfg_rate_bet_beilv[$ret_rate_bet];
    		$user_real_win = $user_win - $bet_total;
    		
    		// 修改金钱
    		$arr_userinfo['cash'] += $user_real_win;
    		
    		if ($user_real_win != 0){
	    		$this->db->update("user", array("cash" => "cash+" . $user_real_win), "uid=" . $uid);
	    	
	    		if ($usermaxpool){
	    			$pool_max -= $user_real_win;
	    			$this->db->update("pool", array("value" => "value-" . $user_real_win), "name='max'");
	    		}else{
	    			$pool_min -= $user_real_win;
	    			$this->db->update("pool", array("value" => "value-" . $user_real_win), "name='min'");
	    		}
    		}
    		
	    	$arr_log_bet['user_win'] = $user_win;// 用户赢的
	    	$arr_log_bet['user_real_win'] = $user_real_win;// 用户减去投注之后赢的	
	    	
	    	$arr_log_bet['pool_min_after'] = $pool_min;
	    	$arr_log_bet['pool_max_after'] = $pool_max;
    		
	    	if (isset($arr_debug[$ret_rate_bet])){	    		
	    		$arr_debug[$ret_rate_bet]['win'] += $user_win;
	    		$arr_debug[$ret_rate_bet]['real_win'] += $user_real_win;
	    		$arr_debug[$ret_rate_bet]['times'] ++;
	    	}else{
	    		$arr_debug[$ret_rate_bet] = array("win" => $user_win, "real_win" => $user_real_win, "times" => 1);
	    	}
	    	
	    	// 返回最终icon计算
	    	$arr_icons = $cfg['bet_icons'][$arr_log_bet['ret_rate_bet']];
	    	$rand_index = array_rand($arr_icons, 1);
	    	$ret_icon = $arr_icons[$rand_index];
	    	$arr_log_bet['ret_icon'] = $ret_icon;
	    	
	    	$arr_log_bet['ip'] = Util::getip(true);
	    	$arr_log_bet['bettime'] = date("Y-m-d H:i:s");
	    	$arr_logs[] = $arr_log_bet;
    	}
    	
    	$this->addlog($arr_logs);
    	
    	$arr_names = array("袁绍","小关羽","小张飞","小大乔", "	小孙权", "小曹操","小夏侯","大夏侯",
			"大曹操","大孙权","大大乔","大张飞","大关羽","小特殊","大特殊");
		$arr_min_names = array("袁绍", "孙权", "大乔", "夏侯惇", "曹操", "关羽", "张飞", "特殊");
				
    	$result = array('status' => 1);
    	$result['cash'] = $this->db->fetchOne("select cash from user where uid=$uid");
    	$result['icon'] = $ret_icon;
    	$result['win'] = $user_win;
    	
    	$result['beilv'] = $cfg_rate_bet_beilv[$ret_rate_bet];
    	$result['bet'] = $arr_bet[$cfg_rate_bet[$ret_rate_bet]];
    	$result['winminicon'] = $cfg_rate_bet[$ret_rate_bet];
    	$result['open'] = $ret_rate_bet;
    	$result['name'] = $arr_names[$ret_rate_bet];
    	$result['minname'] = $arr_min_names[$cfg_rate_bet[$ret_rate_bet]];
    	   	    	
    	if (!$flash){
	    	$result['min'] = $this->db->fetchOne("select value from pool where name='min'");
	    	$result['max'] = $this->db->fetchOne("select value from pool where name='max'");
	    	$str = "";
			ksort ($arr_debug);
	    	foreach ($arr_debug as $index => $v){
	    		$str.=$arr_names[$index] . '(' . $cfg_rate_bet_beilv[$index] .  "倍)开奖：" . $v['times'] . "次 获得奖金：" . $v['win'] . " 扣除投注之后获得奖金：" . $v['real_win'] . "<br />";
	    	}
	    	
	    	$result['str'] = $str;
    	}
    	
    	echo json_encode($result);
    }
    
    /**
     * 添加投注记录
     *
     * @param unknown_type $arr_logs
     */
    private function addlog($arr_logs)
    {
    	$sql = "insert into betlog(";
    	reset($arr_logs);
    	$one_log = current($arr_logs);
    	
    	$comma = "";
    	foreach ($one_log as $key => $v){
    		$sql .= $comma . '`' . $key . '`';
    		$comma = ",";
    	}
    	$sql .= ') values ';
    	
    	$commav = "";
    	foreach ($arr_logs as $v){
    		$sql .= $commav . "(";
    		$comma = "";
    		foreach ($v as $vv){
	    		$sql .= $comma . '"' . $vv . '"';
	    		$comma = ",";
    		}
    		$sql .= ')';
    		$commav = ",";
    	}
    	
    	$this->db->query($sql);
    }
    
    
    /**
     * 登录
     *
     */
    public function dologinAction()
    {
    	$param = $this->getAllParams();
    	
    	if (empty($param['username'])){
    		$this->showmessage(0, "用户名不能为空");
    	}
    	
    	if (empty($param['password'])){
    		$this->showmessage(0, "密码不能为空");
    	}
    	
    	$param['username'] = trim($param['username']);
    	$param['password'] = trim($param['password']);
    	$param['password'] = md5($this->cfg['slot'] . md5($param['password']));
    	
    	$row = $this->db->fetchRow("select * from user where username=\"?\" and password=\"?\"", array($param['username'], $param['password']));
    	if (empty($row))
    		$this->showmessage(0, "账号密码错误！");
    	
    	if ($row['username'] != $param['username'] || $row['password'] != $param['password'])
    		$this->showmessage(0, "账号密码错误！");
    	
    	$_SESSION['uid'] = $row['uid'];
    	
    	$this->showmessage(1, "登录成功！");
    }
    
    /**
     * 退出登录
     *
     */
    public function logoutAction()
    {
    	session_destroy();
    }
    
    
    /**
     * 注册
     *
     */
    public function doregAction()
    {
    	$param = $this->getAllParams();
    	
    	if (empty($param['username'])){
    		$this->showmessage(0, "用户名不能为空");
    	}
    	$param['username'] = trim($param['username']);
    	
    	/**
    	if (!preg_match("/^[a-zA-Z]\\w{5,19}$/",$param['username'])){
    		$this->showmessage(0, "用户名为字母开头，6-20位英文、数字或者下划线");
    	}
    	//**/
    	
    	$model = new UserModel($this->db);
    	
    	$exist = $model->isUsernameExists($param['username']);
    	if ($exist){
    		$this->showmessage(0, "账号已存在！请更换账号");
    	}    	
    	
    	if (empty($param['password'])){
    		$this->showmessage(0, "密码不能为空");
    	}
    	$param['password'] = trim($param['password']);
    	$param['password'] = md5($this->cfg['slot'] . md5($param['password']));
    	
    	$param['cash'] = 0;// 初始金钱
    	    	
    	try{
    		$param['RegIp'] = Util::getip(true);
    		$param['RegTime'] = date("Y-m-d H:i:s");
    		$uid = $model->add($param);
    		$_SESSION['uid'] = $uid;
    		$this->showmessage(1, "注册成功");
    	}catch (Exception $e){
    		$this->showmessage(0, "注册失败，请重试！");
    	}
    }
}
